package com.yonyou.pmclouds.industryandtype.rmiimpl;

import com.alibaba.dubbo.config.annotation.Service;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.industryandtype.entity.IndustryAndTypeRefVO;
import com.yonyou.pmclouds.industryandtype.entity.IndustryVO;
import com.yonyou.pmclouds.industryandtype.entity.TypeVO;
import com.yonyou.pmclouds.industryandtype.rmiitf.IndustryAndTypeQuery;
import com.yonyou.pmclouds.industryandtype.rmiitf.IndustryQuery;
import com.yonyou.pmclouds.industryandtype.rmiitf.TypeQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

@Slf4j
@Service(interfaceClass = IndustryAndTypeQuery.class, version = ApplicationConsts.APPLICATION_VERSION)
public class IndustryAndTypeQueryImpl implements IndustryAndTypeQuery {

    @Autowired
    private IndustryQuery industryQuery;
    @Autowired
    private TypeQuery typeQuery;

    @Override
    public IndustryAndTypeRefVO[] queryIndustryAndType(String billType) throws BusinessException {
        //获取所有的行业节点
        IndustryVO[] industryVOS = industryQuery.queryAllIndustry();
        if(industryVOS == null || industryVOS.length == 0) return new IndustryAndTypeRefVO[0];
        //获取所有行业的主键
        String[] pkIndustry = new String[industryVOS.length];
        for(int i = 0 ; i < industryVOS.length; i++){
            if(industryVOS[i] != null) {
                pkIndustry[i] = industryVOS[i].getPkIndustry();
            }
        }
        //获取所有行业下的对应当前档案类型的类型节点
        TypeVO[] typeVOS = typeQuery.queryTypeByIndustry(pkIndustry, billType);
        //关联行业主键和类型节点
        Map<String, List<TypeVO>> map = new HashMap();
        if(typeVOS != null && typeVOS.length > 0){
            for(TypeVO vo : typeVOS){
                if(vo == null || vo.getPkIndustry() == null) continue;
                if(map.get(vo.getPkIndustry()) == null){
                    map.put(vo.getPkIndustry(), new ArrayList<TypeVO>());
                }
                map.get(vo.getPkIndustry()).add(vo);
            }
        }
        //装入结果集
        List<IndustryAndTypeRefVO> resultList = new ArrayList<>();
        for(IndustryVO industryVO : industryVOS) {
            if(industryVO != null){
                List<TypeVO> typeList = map.get(industryVO.getPkIndustry());
                if(typeList != null && typeList.size() > 0){   //对应的类型不为空
                    IndustryAndTypeRefVO vo = new IndustryAndTypeRefVO();
                    vo.setPkIndustry(industryVO.getPkIndustry());
                    vo.setIndustryName(industryVO.getSname());
                    vo.setTypeVOS(typeList.toArray(new TypeVO[0]));
                    resultList.add(vo);
                }
            }
        }
        return resultList.toArray(new IndustryAndTypeRefVO[0]);
    }
}
